package com.muyi.controller.account;

import com.alibaba.fastjson.JSON;
import com.muyi.service.UserService;
import com.muyi.service.impl.UserServiceImpl;
import com.muyi.util.MD5Util;
import com.muyi.pojo.vo.Result;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "ServletLogin", value = "/login")
public class ServletLogin extends HttpServlet {
    private UserService userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置编码
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        //获取请求参数
        String captcha = request.getParameter("captcha");
        String code = request.getSession().getAttribute("code") + "";
        if (null == captcha || "".equals(captcha) || !code.equalsIgnoreCase(captcha)){
            Result result = new Result(-1, "验证码有误");
            response.getWriter().write(JSON.toJSONString(result));
            return;
        }
        //判断用户名和密码
        String username = request.getParameter("username");
        String pwd = request.getParameter("pwd");
        String s1 = MD5Util.getMD5String(pwd);
        String pwdJM = MD5Util.getMD5String(s1 + MD5Util.SALT);

        Result result = null;
        try {
            result = userService.login(username, pwdJM);
        } catch (Exception e) {
            e.printStackTrace();
        }

        response.getWriter().write(JSON.toJSONString(result));
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
